package cn.tb.basic.service.impl;

import cn.tb.basic.constants.BaseConstants;
import cn.tb.basic.dto.LoginDto;
import cn.tb.basic.dto.WechatDto;
import cn.tb.basic.exception.BusinessException;
import cn.tb.basic.jwt.JwtUtils;
import cn.tb.basic.jwt.LoginResult;
import cn.tb.basic.jwt.RsaUtils;
import cn.tb.basic.service.ILoginService;
import cn.tb.basic.util.AjaxResult;
import cn.tb.basic.util.HttpClientUtils;
import cn.tb.basic.util.MD5Utils;
import cn.tb.basic.util.StrUtils;
import cn.tb.system.domain.Menu;
import cn.tb.system.domain.Permission;
import cn.tb.system.mapper.MenuMapper;
import cn.tb.system.mapper.PermissionMapper;
import cn.tb.user.domain.Logininfo;
import cn.tb.user.domain.User;
import cn.tb.user.domain.Wxuser;
import cn.tb.user.mapper.LogininfoMapper;
import cn.tb.user.mapper.UserMapper;
import cn.tb.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    /**
     * 后端账号密码登录
     * @param dto
     */
    @Override
    public HashMap<String, Object> account(LoginDto dto) {
        String password = dto.getPassword();
        String username = dto.getUsername();
        Integer type = dto.getType();
        //空校验
        if(StringUtils.isEmpty(password) ||StringUtils.isEmpty(username)||StringUtils.isEmpty(type)){
            throw new BusinessException("参数为空");
        }
        //判断账号是否存在 username + type
        //根据username+type查
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
        //判断密码
        //拿不到密码
        if(logininfo==null){
            throw new BusinessException("账号不存在!");
        }
        //拿到密码,判断密码对错
        String salt = logininfo.getSalt();
        String pwdTmp = MD5Utils.encrypByMd5(password + salt);
        //密码错误
        if(!pwdTmp.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误！");
        }
        //密码正确,登录成功
        return loginSuccessHandler(logininfo);

        //存储Redis
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        HashMap<String, Object> map = new HashMap<>();
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        map.put("token",token);
//        map.put("logininfo",logininfo);
//        return map;
    }

    /**
     * 处理登录成功之后的逻辑
     * @param logininfo
     * @return
     */
    private HashMap<String, Object> loginSuccessHandler(Logininfo logininfo) {
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        //1.判断是否是员工，是员工才需要校验权限
        if(logininfo.getType()==0){
            //查询出当前登录人拥有的菜单权限和按钮权限
            //查询出菜单权限
            List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
            //查询出按钮权限
            List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);

        }
        //把登录人信息 + 权限 加密封装成JWT串，返回给前端
        //获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        //使用私钥将loginResult 加密成JWT串
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 60*24);

        HashMap<String, Object> map = new HashMap<>();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("token",jwtStr);
        map.put("logininfo",logininfo);
        map.put("menus",loginResult.getMenus());
        map.put("permissions",loginResult.getPermissions());
        return map;

    }

    /**
     * 微信扫码登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WechatDto dto) {

        String code = dto.getCode();
        if(StringUtils.isEmpty(code)){
               throw new BusinessException("参数为空！");
        }
//        一：微信登录接口
//        1.通过code从微信获取token+openid
        String tokenUrl = BaseConstants.WeChatConstants.TOKEN_URL
                .replace("APPID",BaseConstants.WeChatConstants.APPID)
                .replace("SECRET",BaseConstants.WeChatConstants.SECRET)
                .replace("CODE",code);
        //发送请求到微信
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
        JSONObject tokenObj = JSONObject.parseObject(tokenStr);
        //获取openid
        String openId = tokenObj.getString("openid");
        //获取access_token
        String access_token = tokenObj.getString("access_token");
//      2.通过openid查询t_wxuser表，判断是否wxuser存在并且user_id不为空
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
//      2.1 有，且userId存在，直接免密登录===第二次之后的扫码登录
        if(wxuser!=null && wxuser.getOpenid()!=null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            return AjaxResult.me().setResultObj(loginSuccessHandler(logininfo));


            //存储Redis
//            String token = UUID.randomUUID().toString();
//            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//            //返回token + logininfo
//            HashMap<String, Object> map = new HashMap<>();
//            logininfo.setSalt(null);
//            logininfo.setPassword(null);
//            map.put("token",token);
//            map.put("logininfo",logininfo);
//            return AjaxResult.me().setResultObj(map);
        }
//      2 没有，这里应该让浏览器跳转到绑定页面，让它自己输入账号和密码来完成绑定
//      返回token+openid
        String binderParams = "?accessToken="+access_token+"&openId="+openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
    }

    /**
     * 微信绑定
     * @param dto
     * @return
     */
    @Override
    public HashMap<String, Object> binder(WechatDto dto) {
        String phone = dto.getPhone();
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        String password = dto.getPassword();
        //短信验证码
        String smsCode = dto.getSmsCode();
        //空校验
        if(StringUtils.isEmpty(phone) ||StringUtils.isEmpty(accessToken)||StringUtils.isEmpty(openId)||StringUtils.isEmpty(password)){
            throw new BusinessException("参数为空");
        }
        //判断短信验证码是否正确
        //根据key获取Redis中存的验证码
        String smsCodeKey = BaseConstants.RegisterConstants.BINDER_SMS_PREFIX+phone;
        Object smsTmp = redisTemplate.opsForValue().get(smsCodeKey);
        //拿不到，验证码过期
        if(smsTmp==null){
            throw new BusinessException("验证码已过期！！！");
        }
        //3.3拿到了，判断是否一致
        if(!smsCode.equalsIgnoreCase(smsTmp.toString().split(":")[0])){
            throw new BusinessException("验证码填写错误！！！");
        }
//      1.根据username 查询t_user是否曾今已经存在
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo = null;
//      1.1 存在 查询出来，等着绑定
        if(user!=null){
            logininfo = logininfoMapper.loadByUserId(user.getId());

        }else{
//          1.2 不存在 生成新的t_user + t_logininfo
            //dto转为user
            user = dto2User(dto);
            //user转为logininfo
            logininfo = user2logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }

//      2.根据token + openid 去微信查询微信的用户基本信息
        String wxUserUrl = BaseConstants.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
//      3.根据微信的用户基本信息生成t_wxuser
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
//      4.t_wxuser绑定t_user
        wxuser.setUserId(user.getId());
//      5.保存t_wxuser（完成了整个绑定流程）
        wxuserMapper.save(wxuser);
//      6.直接免密登录
        //存储Redis
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //返回token + logininfo
//        HashMap<String, Object> map = new HashMap<>();
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        map.put("token",token);
//        map.put("logininfo",logininfo);
//        return map;
        return loginSuccessHandler(logininfo);
    }

    private Logininfo user2logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        //一定要手动设置type 1是用户 0是员工
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User(WechatDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        user.setUsername(dto.getPhone());
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        //盐值加密后的密码
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    /**
     * 手机验证码登录
     * @param dto
     * @return
     */
    @Override
    public HashMap<String, Object>  phoneCode(LoginDto dto) {
        String phone = dto.getPhone();
        Integer type = dto.getType();
        //空校验
        String smsCode = dto.getSmsCode();
        if(StringUtils.isEmpty(smsCode)){
            throw new BusinessException("验证码为空");
        }
        //校验账号是否注册过
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(phone, type);
        //没注册过就去注册
        if(logininfo==null){
            throw new BusinessException("账号不存在!!!");
        }
            //注册过下一步
        //校验验证码是否正确
        //3.1根据key获取Redis中存的验证码
        String smsCodeKey = BaseConstants.RegisterConstants.LOGIN_SMS_PREFIX+phone;
        Object smsTmp = redisTemplate.opsForValue().get(smsCodeKey);
        System.out.println(smsTmp.toString().split(":")[0]);
        //3.2拿不到，验证码过期
        if(smsTmp==null){
            throw new BusinessException("验证码已过期！！！");
        }
        //3.3拿到了，判断是否一致
        if(!smsCode.equalsIgnoreCase(smsTmp.toString().split(":")[0])){
            throw new BusinessException("验证码填写错误！！！");
        }
        //正确
        //存储Redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        HashMap<String, Object> map = new HashMap<>();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }

}
